const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const config = require('../config/index')


router.get('/login', async(ctx, next) => {
  let data
  if (ctx.request.query.username === 'admin' && ctx.request.query.password == 'admin') {
    data = {
      user: 'abcdef',
      // 生成 token 返回给客户端
      token: jwt.sign(
        {
          data: 'admin',
          // 设置 token 过期时间
          exp: Math.floor(Date.now() / 1000) + 60 * 60   // 60 seconds * 60 minutes = 1 hour,
        },
        config.secret
      )
    }
  } else {
    data = { code: 20002, message: '账号不存在或密码错误' }
  }
  ctx.body = data
})

router.get('/list', async(ctx, next) => {
  const token = ctx.headers.authorization
  console.log(token)
  try {
    let payload = jwt.verify(token, config.secret) // 解密，获取 payload
    ctx.body = payload.data
  } catch (error) {
    return Promise.reject({ status: 402, message: '未授权' })
  }
})

module.exports = router